package com.beiye.drivertransport.SubActivity;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSON;
import com.beiye.drivertransport.R;
import com.beiye.drivertransport.bean.UpPhotoBean;
import com.beiye.drivertransport.config.AppInterfaceConfig;
import com.beiye.drivertransport.utils.FileUtil;
import com.beiye.drivertransport.utils.ImageUtil;
import com.beiye.drivertransport.utils.LogUtils;
import com.beiye.drivertransport.view.ChangeView;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
//日常检查、安全例检、日排查、行车日志拍照上传
public class TakePhotoVehTeeActivity extends AppCompatActivity {

    private int screenWidth;
    private int screenHeight;
    private File tempFile;
//    //请求访问外部存储
//    private static final int READ_EXTERNAL_STORAGE_REQUEST_CODE = 103;
    //请求写入外部存储
    private static final int WRITE_EXTERNAL_STORAGE_REQUEST_CODE = 104;
    private int type;
    //请求相机
    private static final int REQUEST_CAPTURE = 100;
    private ProgressDialog mProgressDialog;

    //    //请求相册
//    private static final int REQUEST_PICK = 101;
//    //请求截图
//    private static final int REQUEST_CROP_PHOTO = 102;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_take_photo_veh_tee);

        SharedPreferences sp = getSharedPreferences("TAG",
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putInt("TAG", 1);
        editor.commit();
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);// 取得窗口属性
        // 窗口的宽度
        screenWidth = dm.widthPixels;
        // 窗口高度
        screenHeight = dm.heightPixels;
        ViewGroup viewGroup=(ViewGroup)this.findViewById(android.R.id.content);
        ChangeView.changeViewSize(viewGroup, screenWidth, screenHeight);

        //权限判断
        if (ContextCompat.checkSelfPermission(TakePhotoVehTeeActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(TakePhotoVehTeeActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    WRITE_EXTERNAL_STORAGE_REQUEST_CODE);
        } else {
            gotoCamera();
        }


//        SandriosCamera
//                .with(TakePhotoVehTeeActivity.this)
//                .setShowPicker(false)
//                .setShowPickerType(CameraConfiguration.VIDEO)
//                .setVideoFileSize(20)
//                .setMediaAction(CameraConfiguration.MEDIA_ACTION_BOTH)
//                .enableImageCropping(false)
//                .launchCamera(new SandriosCamera.CameraCallback() {
//                    @Override
//                    public void onComplete(CameraOutputModel model) {
////                                LogUtils.e("File", "" + model.getPath());
////                                LogUtils.e("Type", "" + model.getType());
//                        String url = model.getPath();
//                        File file = new File(url);
//                        try {
//                            FileInputStream fis = new FileInputStream(file);
//                            Bitmap bitmapByUrl = BitmapFactory.decodeStream(fis);
//                            bitmapByUrl = compressScale(bitmapByUrl);
//                            bitmapByUrl = rotaingImageView(90, bitmapByUrl);
//                            SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss ");
//                            Date curDate = new Date(System.currentTimeMillis());//获取当前系统时间
//                            String str = formatter.format(curDate);
//
//                            Bitmap bitmap = ImageUtil.drawTextToRightBottom(TakePhotoVehTeeActivity.this, bitmapByUrl, str,ChangeView.adjustFontSize(screenWidth, screenHeight), getResources().getColor(R.color.organger), 5, 5);
//                            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
//                            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
//                            bos.flush();
//                            bos.close();
//                            returnResult(file);
//                        } catch (FileNotFoundException e) {
//                            e.printStackTrace();
//                        } catch (IOException e) {
//
//                        }
//
//
//                    }
//                });

    }

    /**
     * 跳转到照相机
     */
    private void gotoCamera() {
        Log.d("evan", "*****************打开相机********************");
        //创建拍照存储的图片文件
        tempFile = new File(FileUtil.checkDirPath(Environment.getExternalStorageDirectory().getPath() + "/image/"), System.currentTimeMillis() + ".jpg");

        //跳转到调用系统相机
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //设置7.0中共享文件，分享路径定义在xml/file_paths.xml
            intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(TakePhotoVehTeeActivity.this, com.beiye.drivertransport.BuildConfig.APPLICATION_ID + ".fileProvider", tempFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
        } else {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
        }
        startActivityForResult(intent, REQUEST_CAPTURE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        switch (requestCode) {
            case REQUEST_CAPTURE: //调用系统相机返回
                if (resultCode == Activity.RESULT_OK) {
                    Uri uri = Uri.fromFile(tempFile);
                    if (uri == null) {
                        return;
                    }
                    String cropImagePath = FileUtil.getRealFilePathFromUri(TakePhotoVehTeeActivity.this, uri);
                    File file=new File(cropImagePath);
                    try {
                        FileInputStream fis = new FileInputStream(file);
                        Bitmap bitmapByUrl = BitmapFactory.decodeStream(fis);
                        bitmapByUrl = compressScale(bitmapByUrl);
//                            bitmapByUrl = rotaingImageView(90, bitmapByUrl);
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
                        Date curDate = new Date(System.currentTimeMillis());//获取当前系统时间
                        String str = formatter.format(curDate);

                        Bitmap bitmap = ImageUtil.drawTextToRightBottom(TakePhotoVehTeeActivity.this, bitmapByUrl, str,ChangeView.adjustFontSize(screenWidth, screenHeight), getResources().getColor(R.color.organger), 5, 5);
                        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                        bos.flush();
                        bos.close();
                        returnResult(file);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {

                    }

           //         gotoClipActivity(Uri.fromFile(tempFile));
                }
                else if(resultCode==Activity.RESULT_CANCELED)
                {
                    finish();
                }
                break;

//            case REQUEST_PICK:  //调用系统相册返回
//                if (resultCode == Activity.RESULT_OK) {
//                    Uri uri = intent.getData();
//                    gotoClipActivity(uri);
//                }
//                break;
//            case REQUEST_CROP_PHOTO:  //剪切图片返回
//                if (resultCode == Activity.RESULT_OK) {
//                    final Uri uri = intent.getData();
//                    if (uri == null) {
//                        return;
//                    }
//                    String cropImagePath = FileUtil.getRealFilePathFromUri(TakePhotoVehTeeActivity.this, uri);
//                    File file=new File(cropImagePath);
//                    try {
//                            FileInputStream fis = new FileInputStream(file);
//                            Bitmap bitmapByUrl = BitmapFactory.decodeStream(fis);
//                             bitmapByUrl = compressScale(bitmapByUrl);
////                            bitmapByUrl = rotaingImageView(90, bitmapByUrl);
//                            SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss ");
//                            Date curDate = new Date(System.currentTimeMillis());//获取当前系统时间
//                            String str = formatter.format(curDate);
//
//                            Bitmap bitmap = ImageUtil.drawTextToRightBottom(TakePhotoVehTeeActivity.this, bitmapByUrl, str,ChangeView.adjustFontSize(screenWidth, screenHeight), getResources().getColor(R.color.organger), 2, 2);
//                            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
//                            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
//                            bos.flush();
//                            bos.close();
//                            returnResult(file);
//                        } catch (FileNotFoundException e) {
//                            e.printStackTrace();
//                        } catch (IOException e) {
//
//                        }
//
//                }
//                break;
        }
    }


    private void returnResult(File file) {
        Uri uri = Uri.fromFile(file);
        String url = uri.toString().substring(uri.toString().indexOf("///") + 2);

        uploadImg(url,file);
    }
    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
    private final OkHttpClient client = new OkHttpClient();
    private void uploadImg(final String url, File mediaFile) {
        // mImgUrls为存放图片的url集合
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);

        if (mediaFile != null) {
            builder.addFormDataPart("vehExamImg", mediaFile.getName(), RequestBody.create(MEDIA_TYPE_PNG, mediaFile));
            builder.addFormDataPart("oprType","6");
        }
        mProgressDialog = new ProgressDialog(TakePhotoVehTeeActivity.this,ProgressDialog.THEME_HOLO_DARK);
        mProgressDialog.setMessage("上传中...");
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mProgressDialog.setCancelable(false);
        mProgressDialog.show();

        MultipartBody requestBody = builder.build();
        //构建请求
        Request request = new Request.Builder()
                .url(AppInterfaceConfig.BASE_URL + "app/vehTeeExam/uploadImg")//地址
                .post(requestBody)//添加请求体
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                LogUtils.e("上传失败", e.getLocalizedMessage());
                mProgressDialog.dismiss();
                // 设置回传码和Intent
                setResult(2, null);
                finish();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {

                mProgressDialog.dismiss();
                String str = response.body().string();
                LogUtils.e("上传成功", str);
                UpPhotoBean upPhotoBean = JSON.parseObject(str, UpPhotoBean.class);
                String data = upPhotoBean.getData();
                boolean result = upPhotoBean.isResult();
                if(result)
                {
                    Intent intent = new Intent();
                    // 设置要回传的数据
                    intent.putExtra("url", data);
                    intent.putExtra("localurl", url);
                    // 设置回传码和Intent
                    setResult(1, intent);
                    finish();
                }else{
                    LogUtils.e("上传空值", data);
                    setResult(2, null);
                    finish();
                }

                LogUtils.e("上传图片", data);

            }
        });

    }


    /**
     * 外部存储权限申请返回
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == WRITE_EXTERNAL_STORAGE_REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
                gotoCamera();
            }
        }
//        else if (requestCode == READ_EXTERNAL_STORAGE_REQUEST_CODE) {
//            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                // Permission Granted
//                gotoPhoto();
//            }
//        }
    }

    //图片旋转
    public static Bitmap rotaingImageView(int angle, Bitmap bitmap) {
        //旋转图片 动作
        Matrix matrix = new Matrix();
        ;
        matrix.postRotate(angle);
        System.out.println("angle2=" + angle);
        // 创建新的图片
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        return resizedBitmap;
    }
    /**
     * 图片按比例大小压缩方法
     *
     * @param image （根据Bitmap图片压缩）
     * @return
     */
    public static Bitmap compressScale(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        // 判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出
        if (baos.toByteArray().length / 1024 > 1024) {
            baos.reset();// 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, 80, baos);// 这里压缩50%，把压缩后的数据存放到baos中
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        // 开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        //Log.i(TAG, w + "---------------" + h);
        // 现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
        // float hh = 800f;// 这里设置高度为800f
        // float ww = 480f;// 这里设置宽度为480f
        float hh = 600f;
        float ww = 450f;
        // 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;// be=1表示不缩放
        if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) { // 如果高度高的话根据高度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be; // 设置缩放比例
        // newOpts.inPreferredConfig = Config.RGB_565;//降低图片从ARGB888到RGB565
        // 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        isBm = new ByteArrayInputStream(baos.toByteArray());
        bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
        return bitmap;
        //return bitmap;
    }



}